package com.example.netty.实现客户端与服务端信息收发;

import com.example.netty.encode.Packet.MessageRequestPacket;
import com.example.netty.encode.Packet.PackerCode;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author liupk
 * @date 2018/10/25
 */
public class NettyClient {
    
    private static ExecutorService pool = Executors.newFixedThreadPool(1);
    
    public static void main(String[] args) {
        
        Bootstrap bootstrap = new Bootstrap();
        NioEventLoopGroup worker = new NioEventLoopGroup();
        bootstrap.group(worker)
                 .channel(NioSocketChannel.class)
                 .handler(new ChannelInitializer<NioSocketChannel>() {
                     @Override
                     protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new ClientHandle());
                     }
                 });
        
        bind(bootstrap,"127.0.0.1",8000);
    }
    
    private static void bind(Bootstrap bootstrap, String host, int port) {
        bootstrap.connect(host, port).addListener(future -> {
            if (future.isSuccess()) {
                Channel channel = ((ChannelFuture) future).channel();
                /**连接成功之后，启动控制台线程*/
                startConsoleThread(channel);
            }
        });
    }
    
    private static void startConsoleThread(Channel channel) {
        new Thread(()-> {
            /**线程未中断*/
            while (!Thread.interrupted()) {
                /**如果登陆过就开启控制台*/
                if (LoginUtil.hasLogin(channel)) {
                    System.out.println("输入消息发送至服务端: ");
                    Scanner sc = new Scanner(System.in);
                    String line = sc.nextLine();
                    /**发消息给服务端*/
                    MessageRequestPacket packet = new MessageRequestPacket();
                    packet.setMessage(line);
                    ByteBuf byteBuf = PackerCode.getINSTANCE().encode(channel.alloc().ioBuffer(), packet);
                    channel.writeAndFlush(byteBuf);
                }
            }
        }).start();
//        pool.shutdown();
    }
}